using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Nop.Data
{
	public static class SQLDispatcherConfiguration
	{
		public static DB WritableDB { get; set; }
		public static List<DB> ReadDBs { get; set; }
		public static List<DedicatedRegion> DedicatedRegions { get; set; }

		public static void Load()
		{
			WritableDB = null;
			ReadDBs = new List<DB>();
			DedicatedRegions = new List<DedicatedRegion>();

			XElement root = XElement.Load(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sqldispatcher.config"));

			root = root.Element("SQLDispatcher");
			if (root == null)
				throw new Exception("SQLDispatcher node not exists");



			WritableDB = new DB() { ConnectionString = root.Element("WritableDB").Value };

			foreach (var elm in root.Element("ReadDBs").Elements("DB"))
			{
				DB db = new DB();
				db.ConnectionString = elm.Value;
				ReadDBs.Add(db);
			}
			if (root.Element("DedicatedReadDBs") != null)
			{
				foreach (var elm in root.Element("DedicatedReadDBs").Elements("DedicatedRegion"))
				{
					DedicatedRegion region = new DedicatedRegion();

					region.Region = elm.Element("Region").Value;
					foreach (var elmInner in elm.Elements("DB"))
					{
						DB db = new DB();
						db.ConnectionString = elmInner.Value;
						region.DBs.Add(db);
					}

					DedicatedRegions.Add(region);
				}
			}

			if (WritableDB == null || WritableDB.ConnectionString.Length == 0)
				throw new Exception("Please specify writable db info");
			if (ReadDBs.Count == 0)
				throw new Exception("Please specify readable db info");
		}	

		static SQLDispatcherConfiguration()
		{
			Load();
		}
	}

	public class DB
	{
		//public int Weight { get; set; }
		public string ConnectionString { get; set; }
	}

	public class DedicatedRegion
	{
		public DedicatedRegion()
		{
			DBs = new List<DB>();
		}
		public string Region { get; set; }
		public List<DB> DBs { get; set; }
	}
}
